
/**
 * 
 * @param {需要运动的节点} eleNode 
 * @param {要改变的属性} options 
 * @param {结束回调函数} callback 
 * @param {每次调用函数} callback2
 * 比如 move(box,{
                    height : 100,
                    width : 100,
                    opacity : 100
                },startMove);
 */
function move(eleNode,options,callback, callback2){
    clearInterval(eleNode.timer);
    eleNode.timer = setInterval(function(){
        var count = 0;
        for(var attr in options){
            // 把每个属性的结果都返回出来放在数组之中
            count ++;
            var result =  attrToTarget(eleNode,attr,options[attr]);
            if(result){
                    delete options[attr];
            }
        }
            
        if(count === 0){
            clearInterval(eleNode.timer);
            move.timerList.splice(move.timerList.indexOf(eleNode.timer),1);
            if(typeof callback === "function")
                callback();
            return false;
        }

        if(typeof callback2 === "function")
            callback2();
    },50)

    if(move.timerList instanceof Array){
          move.timerList.push(eleNode.timer);
    }else{
          move.timerList = [eleNode.timer];    
    }
}
function attrToTarget(eleNode,attr,target){
    var gs = getComputedStyle;
    if(attr === "opacity"){
          var iNow = gs(eleNode)[attr] * 100
    }else{
          var iNow = parseInt(gs(eleNode)[attr]);
    }

    var speed = (target - iNow) / 8;
    speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

    iNow += speed;

    if(attr === "opacity"){
          eleNode.style[attr] = iNow / 100;
    }else{
          eleNode.style[attr] = iNow + "px";
    }

    return iNow === target;
}
function stop(){
    for(; move.timerList[0]; ){
          clearInterval(move.timerList.pop());
    }
}

/**
 * 
 * 利用xhr发送get请求;
 * 
 */
function xhrGet(url,data){
    return new Promise((resolve, reject)=>{
        var xhr = new XMLHttpRequest();
        if(typeof data !== "function" && data instanceof Object){
            // 拼接字符串; 
            var _arr = [];
            for(var key in data){
                    _arr.push( `${key}=${data[key]}`)
            }     
            var _symbol = /\?/.test(url) ? "&" : "?";
            url += _symbol + _arr.join("&")
        }
        xhr.open("GET",url);
        xhr.send(null);
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200)
                resolve(xhr.responseText);
                
        }
    })
}
/**
 * 
 *利用xhr发送post请求;
 * 
 */
function xhrPost(url,data){
    return new Promise((resolve,reject)=>{
        var xhr = new XMLHttpRequest();
        xhr.open("POST",url);
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        var _data = [];
        for(let key in data){
                _data.push(`${key}=${data[key]}`);
        }
        xhr.send(_data.join("&"));
        xhr.onload = function(){
                xhr.status === 200 ? resolve(xhr.responseText) : reject(xhr.status);
        }
    })
}
/**
 * 
 * @param {*地址 } url 
 * @param {*可选参数 ，回调函数名，默认为 callback} cb_key 
 * @param {*传输数据，传输类型仅限于 GET} data 
 */
function jsonp(url,cb_key,data){
    cb_key = !cb_key ? "callback" : cb_key; 

    data = !data ? {} : data;
    return new Promise((resove,reject)=>{
          var cb_name = "gp10" + Date.now();
          window[cb_name] = function(res){
                resove(res);
          } 
          var script = document.createElement("script");
          url += /\?/.test(url) ? "&" : "?";
          url += cb_key + "=" + cb_name;
          for(let key in data){
                url += `&${key}=${data[key]}`;
          }


          script.src = url ;
          document.body.appendChild(script);
          script.onload = function(){
                this.remove();
          }
    })
}

/**
 * 
 *  设置cookie功能;
 * 
 * 
 */
function cookie(key,value,options){
    var res = "";
    typeof options === "object" ? Object.assign({},options) : options = {}; 
    res += key + "=" + encodeURI(value);
    // 有没有过期时间;
    if(typeof options.expires === "number"){
          let d = new Date()
          d.setDate(d.getDate() + options.expires);
          res += ";expires="+d;
    }
    res += options.path ? ";path="+options.path : "";
    res += options.domain ? ";domain="+options.domain : "";

    document.cookie = res;
}
/**
 * 
 * 删除cookie
 */
function removeCookie(key,options){
    // 确保options一定是对象类型,同时可以配置默认参数;
    let default_options = {
          expires : -1
    };
    options = typeof options =="object" ? Object.assign(default_options,options) : default_options;
    cookie(key,null,options)
}
/**
 * 
 * 通过key得到cookie
 */
function getCookie(key){
    var _cookie = document.cookie;
    // "key=value; key2=value; key3=value";
    var _cookie_item = _cookie.split("; ");
    var _key = [];
    var _value = _cookie_item.map( item => {
          var _temp = item.split("=");
          _key.push(_temp[0]);
          return _temp[1];
    })
    var index = _key.indexOf(key);
    if(index !== -1){
          return _value[index];
    }
    return "";
}

module.exports = {
    move,
    xhrGet,
    xhrPost,
    jsonp,
    cookie,
    removeCookie,
    getCookie
}